package com;

import okhttp3.*;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.concurrent.TimeUnit;

/**
 * 图床API客户端
 */
public class PicBedClient {
    private final String baseUrl;
    private final String token;
    private final OkHttpClient httpClient;

    public PicBedClient(String baseUrl, String token) {
        this.baseUrl = baseUrl;
        this.token = token;
        this.httpClient = new OkHttpClient.Builder()
                .connectTimeout(100000, TimeUnit.SECONDS)
                .build();
    }

    /**
     * 获取用户信息
     */
    public String getUserInfo() throws IOException {
        Request request = new Request.Builder()
                .url(baseUrl + "/user/info")
                .header("Authorization", "Bearer " + token)
                .get()
                .build();

        try (Response response = httpClient.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("获取用户信息失败: " + response);
            }
            return response.body().string();
        }
    }

    /**
     * 获取上传策略列表
     */
    public String getUploadStrategies() throws IOException {
        Request request = new Request.Builder()
                .url(baseUrl + "/upload/strategy/list")
                .header("Authorization", "Bearer " + token)
                .get()
                .build();

        try (Response response = httpClient.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("获取上传策略列表失败: " + response);
            }
            return response.body().string();
        }
    }

    /**
     * 生成临时上传Token
     */
    public String generateUploadToken(int num, int seconds) throws IOException {
        // 验证参数
        if (num <= 0 || num > 100) {
            throw new IllegalArgumentException("生成数量必须在1-100之间");
        }
        if (seconds <= 0 || seconds > 2626560) {
            throw new IllegalArgumentException("有效期必须在1-2626560秒之间");
        }

        // 构建JSON请求体
        String jsonBody = String.format("{\"num\":%d,\"seconds\":%d}", num, seconds);

        Request request = new Request.Builder()
                .url(baseUrl + "/images/tokens")
                .header("Authorization", "Bearer " + token)
                .header("Accept", "application/json")
                .post(RequestBody.create(MediaType.parse("application/json"), jsonBody))
                .build();

        try (Response response = httpClient.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("生成上传Token失败: " + response);
            }
            return response.body().string();
        }
    }

    /**
     * 上传图片
     */
    public String uploadImage(File imageFile, String uploadToken) throws IOException {
        // 创建请求体
        RequestBody fileBody = RequestBody.create(MediaType.parse(Files.probeContentType(imageFile.toPath())), imageFile);
        MultipartBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", imageFile.getName(), fileBody)
                .addFormDataPart("token", uploadToken)
                .addFormDataPart("permission","1")
                .addFormDataPart("strategy_id", "9")
                .build();

        // 创建请求
        Request request = new Request.Builder()
                .url(baseUrl + "/upload")
                .header("Authorization", "Bearer " + token)
                .header("Accept", "application/json")
                .post(requestBody)
                .build();

        // 执行请求并获取响应
        try (Response response = httpClient.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("上传失败: " + response);
            }
            return response.body().string();
        }
    }
}